package src.DButils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class EmpDaolmpl {
    private QueryRunner queryRunner = new QueryRunner();

    /*
     * 1.查询所有的数据
     * */
    public List<Emp> selectAll() {

        try {
            List<Emp> emps = queryRunner.query(DbUtils.getConnection(), "select* from emp",
                    new BeanListHandler<Emp>(Emp.class));
            return emps;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    /*
     * 2.实现删除的业务逻辑接口
     * */
    public int delete(int id) {
        try {
            int result = queryRunner.update(DbUtils.getConnection(),"delete from emp where id=?;", id);
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    /*
     * 3.更新的业务逻辑
     * */
    public int update(Emp emp) {
        try {
            int result = queryRunner.update(DbUtils.getConnection(),"update emp set name=?,salary=?,age=? where id=?;",
                    emp.getName(),emp.getSalary(), emp.getAge(), emp.getId());

            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    /*
     * 选择一条数据
     * */
    public Emp select(int id) {
        System.out.println("数据操作层：id = " + id);
        try {
            Emp emp = queryRunner.query(DbUtils.getConnection(),"select * from emp where id=?;", new BeanHandler<Emp>(Emp.class), id);

            return emp;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /*
     * 插入一条数据
     * */
    public int insert(Emp emp) {
        System.out.println("数据操作的DAO：emp.toString() = " + emp.toString());
        try {
            int result = queryRunner.update(DbUtils.getConnection(),
                    "insertinto emp(name,salary,age) values(?,?,?);",
                    emp.getName(),emp.getSalary(), emp.getAge());
            System.out.println("数据入库成功啦--result =" + result);
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
